package com.example.yucheng.controller;

import com.example.yucheng.domain.Category;
import com.example.yucheng.service.CategoryService;
import com.example.yucheng.util.PageQuery;
import com.example.yucheng.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//分类接口
@RestController
@CrossOrigin
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    @GetMapping("/getCategoryList")
    public Result getCategoryByLimit(@RequestParam(required = false) Integer pageNum,@RequestParam(required = false) Integer pageSize,@RequestParam(required = false)  Integer sort ){
        int total = categoryService.getAllCategory().size();
        if (pageNum==null){
            List<Category> allCategory = categoryService.getAllCategory();
            return Result.success(allCategory);
        }else{
            List<Category> categoryByLimit = categoryService.getCategoryByLimit(new PageQuery((pageNum-1)*pageSize, pageSize, sort));
            Map re = new HashMap();
            re.put("categoryList",categoryByLimit);
            re.put("total",total);
            return Result.success(re);
        }
    }


    @DeleteMapping("/deleteCategory")
    public Result deleteCategoryById(@RequestParam int[] ids){
        int deleteCategorytById =0;
        for (Integer temp:ids){
            deleteCategorytById = categoryService.deleteCategorytById(temp);
        }
        if (deleteCategorytById==1){
            return Result.success("删除成功");
        }else{
            return Result.success("删除失败");
        }


    }

    @PutMapping("/addCategory")
    public Result addCategory(@RequestBody Category category)  {
        System.out.println(category);
        String s = categoryService.selectCategoryName(category.getName());
        if (s!=null){
            return Result.success("已存在");
        }
        int add = categoryService.insertCategory(category);
        if (add==1){
            return Result.success("添加成功");
        }else{
            return Result.success("添加失败");
        }

    }

    @PutMapping("/updateCategory")
    public Result updateCategory(@RequestBody Category category){
        int updateCategory = categoryService.updateCategory(category);
        if (updateCategory==1){
            return Result.success("更改成功");
        }
        return Result.success("更改失败");
    }

}
